# encoding:utf-8
import cv2
from PySide6.QtGui import QPixmap, QImage
import numpy as np
from PIL import Image,ImageDraw,ImageFont
import csv
import pandas as pd
# 车牌识别包
from hyperlpr import *

pd.set_option('mode.chained_assignment', None)

# 车牌标注的字体
fontC = ImageFont.truetype("Font/platech.ttf", 20, 0)

# 绘图展示
def cv_show(name,img):
	cv2.imshow(name, img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()



def drawRectBox(image, rect, addText, fontC):
    """
    车牌识别，绘制矩形框与结果
    :param image: 原始图像
    :param rect: 矩形框坐标
    :param addText:车牌号
    :param fontC: 字体
    :return:
    """
    # 绘制车牌位置方框
    cv2.rectangle(image, (int(round(rect[0])), int(round(rect[1]))),
                 (int(round(rect[2]) + 15), int(round(rect[3]) + 15)),
                 (0, 0, 255), 2)
    # 绘制字体背景框
    cv2.rectangle(image, (int(rect[0] - 1), int(rect[1]) - 25), (int(rect[0] + 120), int(rect[1])), (0, 0, 255), -1, cv2.LINE_AA)
    img = Image.fromarray(image)
    draw = ImageDraw.Draw(img)
    draw.text((int(rect[0] + 1), int(rect[1] - 25)), addText, (255, 255, 255), font=fontC)
    imagex = np.array(img)
    return imagex

def info_entry_detect(img):
    """
    识别车牌号
    :param img:
    :return:
    """
    res_all = HyperLPR_plate_recognition(img)

    if len(res_all) == 0:
        return img, None, None
    # 车牌号、置信度、车牌区域
    res, conf, boxes = res_all[0]
    image = drawRectBox(img, boxes, res, fontC)
    return image, res, boxes


def img_cvread(path):
    # img = cv2.imread(path)
    img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR)
    return img


def draw_boxes(img, boxes):
    for each in boxes:
        x1 = each[0]
        y1 = each[1]
        x2 = each[2]
        y2 = each[3]
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
    return img


def cvimg_to_qpiximg(cvimg):

    height, width, depth = cvimg.shape
    cvimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB)
    qimg = QImage(cvimg.data, width, height, width * depth, QImage.Format_RGB888)
    qpix_img = QPixmap(qimg)
    return qpix_img


def save_video():
    # VideoCapture方法是cv2库提供的读取视频方法
    cap = cv2.VideoCapture('C:\\Users\\xxx\\Desktop\\sweet.mp4')
    # 设置需要保存视频的格式“xvid”
    # 该参数是MPEG-4编码类型，文件名后缀为.avi
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    # 设置视频帧频
    fps = cap.get(cv2.CAP_PROP_FPS)
    # 设置视频大小
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    # VideoWriter方法是cv2库提供的保存视频方法
    # 按照设置的格式来out输出
    out = cv2.VideoWriter('C:\\Users\\xxx\\Desktop\\out.avi', fourcc, fps, size)

    # 确定视频打开并循环读取
    while (cap.isOpened()):
        # 逐帧读取，ret返回布尔值
        # 参数ret为True 或者False,代表有没有读取到图片
        # frame表示截取到一帧的图片
        ret, frame = cap.read()
        if ret == True:
            # 垂直翻转矩阵
            frame = cv2.flip(frame, 0)

            out.write(frame)

            cv2.imshow('frame', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

    # 释放资源
    cap.release()
    out.release()
    # 关闭窗口
    cv2.destroyAllWindows()


# 封装函数:图片上显示中文
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=50):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


def insert_rows(path, lines ,header):
    """
    将n行数据写入csv文件
    :param path:
    :param lines:
    :return:
    """
    no_header = False
    if not os.path.exists(path):
        no_header = True
        start_num = 1
    else:
        start_num = len(open(path).readlines())

    csv_head = header
    with open(path, 'a', newline='') as f:
        csv_write = csv.writer(f)
        if no_header:
            csv_write.writerow(csv_head)  # 写入表头

        for each_list in lines:
            # 添加序号
            each_list = [start_num] + each_list
            csv_write.writerow(each_list)
            # 序号 + 1
            start_num += 1


def creat_csv(path,header=None):
    """
    创建csv文件
    :param path: 文件路径
    :param header: 文件头
    :return:
    """
    with open(path, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(header)

def read_csv(path):
    """
    读取csv文件
    :param path:
    :return:
    """
    # data = pd.read_csv(path, sep=',', encoding='gbk', converters={'ID': str})
    data = pd.read_csv(path, sep=',', encoding='gbk')
    return data


def save_csv_data(df, path):
    """
    保存修改后的识别数据
    :param df:
    :param path:
    :return:
    """
    df['序号'] = range(1, len(df) + 1)
    df.to_csv(path, index=False,encoding='gbk')

def get_remaining_num(pd_dada):
    """
    计算剩余车位数
    :param pd_dada:
    :return:
    """
    df1 = pd_dada.groupby(['车辆牌照'])['序号'].count()
    # 数据库中已进入车辆 + 当前进入1辆车
    entry_num = sum(df1 % 2 == 1) + 1
    return entry_num